import constants from '@/constants';
import { YopService } from '@/core/yop.service';
import { CurrentUser, Public } from '@/decorators';
import { OrderListDto, OrderPayDto, OrderQueryDto } from '@/dtos';
import { PaymentTypeEnum } from '@/enums';
import { OrderService } from '@/services/order.service';
import { ok } from '@/utils';
import { InjectQueue } from '@nestjs/bull';
import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Query,
} from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
import { Queue } from 'bull';
import { BaseController } from './base.controller';
import { HuifuService } from '@/core/huifu.service';

@Controller('order')
export class OrderController extends BaseController {
  constructor(
    @InjectQueue('order')
    private readonly orderQueue: Queue,
    private readonly orderService: OrderService,
    private readonly yopService: YopService,
    private readonly huifuService: HuifuService,
  ) {
    super();
  }

  @Public()
  @Post('callback')
  @SkipThrottle()
  async callback(@Body() dto: any) {
    console.log('@@@支付回调POST', dto);
    if (this.config.get('payment') === PaymentTypeEnum.YOP) {
      const res = await this.yopService.verifySign(dto.response);
      if (res && res?.status === 'SUCCESS') {
        await this.orderQueue.add('cancel', {
          no: res.orderId,
        });
      }
      return 'SUCCESS';
    }
    if (this.config.get('payment') === PaymentTypeEnum.HUIFU) {
      const res = await this.huifuService.verifySign(dto.check_value);
      if (res && res?.resp_code === 'C00000') {
        await this.orderQueue.add('cancel', {
          no: res?.order_id,
        });
      }
      return 'SUCCESS';
    }
    if (this.config.get('payment') === PaymentTypeEnum.SNAD) {
      return 'respCode=000000';
    }
  }

  @Public()
  @Get('callback')
  @SkipThrottle()
  async getCallback(
    @Body() dto: any,
    @Query() query: any,
    @Param() params: any,
  ) {
    console.log('---支付回调GET', dto, query, params);
  }

  @Post('list')
  async getList(@Body() dto: OrderListDto, @CurrentUser('id') userId: number) {
    return ok(
      await this.orderService.getList({
        ...dto,
        userId,
      }),
    );
  }

  @Get(':no')
  async getOrderByNo(@Param('no') no: string) {
    return ok(await this.orderService.getOrderByNo(no));
  }

  @Post('pay')
  async pay(@Body() dto: OrderPayDto, @CurrentUser('id') id: number) {
    return ok(await this.orderService.pay(dto, id));
  }

  @Delete(':no')
  async cancelOrderByNo(
    @Param('no') no: string,
    @CurrentUser('id') id: number,
  ) {
    return ok(await this.orderService.cancelOrderByNo(no, id));
  }

  @Post('admin/query')
  async query(@Body() dto: OrderQueryDto) {
    return ok(await this.orderService.query(dto));
  }

  @Get('admin/:no/orders')
  async getSubOrders(@Param('no') no: string) {
    return ok(await this.orderService.getSubOrders(no));
  }
}
